// Package app 需要注册的后台服务
package app

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"golang.org/x/sync/errgroup"
	"hcy-api/lib/middleware"
	"vap/daemon/gua"
	"vap/daemon/tcp"
	"vap/global"
	"vap/module/api"
)

type Daemon struct {
	exitFunc context.CancelFunc
}

func NewDaemon() *Daemon {
	return &Daemon{}
}

// Run runs the service and blocks until complete.
func (d *Daemon) Run(parentCtx context.Context) {
	var (
		g   errgroup.Group
		err error
	)
	ctx, cancelFunc := context.WithCancel(parentCtx)
	d.exitFunc = cancelFunc
	// 初始化数据库
	global.InitDB()
	// 初始化 gua manager
	gua.NewManager()

	// 启动tcp服务
	g.Go(func() error {
		defer func() {
			logrus.Errorf("tcp server exit，err:%s", err)
		}()
		err = tcp.NewServer(global.Conf.TcpServ.Address)
		return err
	})
	// 启动http服务
	g.Go(func() error {
		defer func() {
			logrus.Errorf("http服务运行时发生错误：%s", err)
		}()
		// 初始化http服务
		app := gin.New()
		r := app.Group(httpApiPrefix)
		r.Use(middleware.HttpLog())
		api.RegisterRouter(r)
		err = app.Run(global.Conf.Http.Addr)
		return err
	})

	g.Go(func() error {
		defer func() {
			logrus.Debug("优雅关闭,协程-已退出")
			cancelFunc()
		}()
		<-ctx.Done()
		return nil //nolint
	})

	err = g.Wait()
	if err != nil {
		logrus.Debugf("shutting down the server: %v", err)
	}

}
